<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/4/18 0018
 * Time: 21:50
 */

error_reporting(E_ALL);
set_time_limit(0);
echo "<h2>TCP/IP Connection</h2>\n";

$port_file = './port.txt';
$fp = fopen($port_file, 'r');
$port = fgets($fp, 1024);
fclose($fp);
$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($sock < 0) {
    echo "socket_create() failed: reason: " . socket_strerror($sock) . "\n";
} else {
    echo "OK.\n";
}

$result = socket_connect($sock, '127.0.0.1', $port);
if ($sock < 0) {
    echo "socket_connect() failed.\nReason: ($result) " . socket_strerror($result) . "\n";
} else {
    echo "连接OK\n";
}
$in = '向服务端发送消息';
if (!socket_write($sock, $in, strlen($in))) {
    echo "socket_write() failed: reason: " . socket_strerror($sock) . "\n";
}else{
    echo "发送到服务器信息成功！\n";
    echo "发送的内容为:<font color='red'>$in</font> <br>";
}

while($out = socket_read($sock, 8192)) {
 echo "接收服务器回传信息成功！\n";
  echo "接受的内容为:",$out;
}
socket_close($sock);